﻿using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using ShakeGestures;
using System;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace A_larm_Shake
{
    public partial class page_timer : PhoneApplicationPage
    {
        private DateTime EndTime { get; set; }
        private DispatcherTimer dispatcherTimer;
        private string descrip = "", spanx = "",lv = "";
        private int count;
        private string Svalue;
   
        IsolatedStorageSettings setvalue = IsolatedStorageSettings.ApplicationSettings;

        MessageBoxButton buttons = MessageBoxButton.OK;
        MessageBoxResult result;

        /*-------------------------------------------- On load --------------------------------------------*/

        #region Onload
        public page_timer()
        {
            InitializeComponent();
            Loaded += page_timer_Loaded;
            count = 0;
                   
            this.tb1.Text = "--:--:--";
            this.tb4.Text = "count = "+count;
            this.tb3.Text = lv;
            this.EndTime = DateTime.MinValue;
            this.timeSpan.Value = TimeSpan.FromSeconds(0);

            PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            PhoneApplicationFrame rootFrame = App.Current.RootVisual as PhoneApplicationFrame;
        }

        private void page_timer_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this.EndTime = DateTime.MinValue;
            if (IsolatedStorageSettings.ApplicationSettings.Contains("TimerData1"))
            {
                spanx =
                IsolatedStorageSettings.ApplicationSettings["TimerData1"] as string;
                lv =
                IsolatedStorageSettings.ApplicationSettings["TimerData2"] as string;
                descrip =
                IsolatedStorageSettings.ApplicationSettings["TimerData3"] as string;
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains("Setvalue"))
            {
                Svalue =
                IsolatedStorageSettings.ApplicationSettings["Setvalue"] as string;
            }

            tb2.Text = lv;
            tb3.Text = "Descript = " + descrip;

            if (lv == "1" || lv == "2" || lv == "3")
            {
                bt_StartTimer.IsEnabled = true;
                bt_CancelTimer.IsEnabled = true;
                this.tb1.Text = spanx;
            }
            else
            {
                bt_StartTimer.IsEnabled = false;
                bt_CancelTimer.IsEnabled = false;
            }

            if (Svalue != null)
            {
                if (Svalue == "on")
                {
                    var remaining = this.EndTime - DateTime.Now;
                    int remainingSeconds = (int)remaining.TotalSeconds;
                    this.timeSpan.Value = TimeSpan.FromSeconds(remainingSeconds);

                    if (remaining.TotalSeconds <= 0)
                    {
                        this.mesound.Play();
                        this.mesound.MediaEnded += new RoutedEventHandler(mediaElement1_MediaEnded);

                        ShakeGesturesHelper.Instance.ShakeGesture +=
                                new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);
                        ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 4;
                        ShakeGesturesHelper.Instance.Active = true;
                    }
                 }
                if (Svalue == "off")
                {
                    testx();
                    if (!setvalue.Contains("Setvalue"))
                    {
                        setvalue.Add("Setvalue", Svalue);
                    }
                    else
                    {
                        setvalue["Setvalue"] = Svalue;
                    }

                }
            }
        }

        #endregion

        /*-------------------------------------------- Click Bt --------------------------------------------*/

        #region Button Click

        private void bt_StartTimer_Click(object sender, RoutedEventArgs e)
        {
            startpro();
            if (ScheduledActionService.Find("timerremind") != null)
                ScheduledActionService.Remove("timerremind");

            Reminder re = new Reminder("timerremind");
            re.Title = "A-larm Shake Reminder";
            re.Content = descrip + "By A-larm shake";
            re.NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative);
            re.BeginTime = DateTime.Now + TimeSpan.Parse(spanx);
            re.ExpirationTime = DateTime.Now.AddDays(7);
            re.RecurrenceType = RecurrenceInterval.Daily;

            ScheduledActionService.Add(re);

        }

        private void bt_CancelTimer_Click(object sender, RoutedEventArgs e)
        {
            stoppro();

            if (ScheduledActionService.Find("timerremind") != null)
                ScheduledActionService.Remove("timerremind");
        }

        private void bt_setTimer_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/page_setTimer.xaml", UriKind.Relative));
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //this.NavigationService.RemoveBackEntry();

            if (!setvalue.Contains("Setvalue"))
            {
                setvalue.Add("Setvalue", Svalue);
            }
            else
            {
                setvalue["Setvalue"] = Svalue;
            }
            setvalue.Save();
            base.OnBackKeyPress(e);
        }
        #endregion

        /*-------------------------------------------- End Click --------------------------------------------*/
        #region Timer
        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            var remaining = this.EndTime - DateTime.Now;
            int remainingSeconds = (int)remaining.TotalSeconds;
            this.timeSpan.Value = TimeSpan.FromSeconds(remainingSeconds);

            string str = null;
            str = String.Format("{0:D2}:{1:D2}:{2:D2}",
                               remaining.Hours, remaining.Minutes,
                               remaining.Seconds);

            this.tb1.Text = str;

            if (remaining.TotalSeconds <= 0)
            {
                this.mesound.Play();
                this.mesound.MediaEnded += new RoutedEventHandler(mediaElement1_MediaEnded);
                sys_warn();

                ShakeGesturesHelper.Instance.ShakeGesture +=
                        new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);
                ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 4;
                ShakeGesturesHelper.Instance.Active = true;
            }
            
        }
        #endregion

        #region Alarm Sys

        private void sys_warn()
        {
            this.dispatcherTimer.Stop();
            this.EndTime = DateTime.MinValue;
            this.timeSpan.Value = TimeSpan.FromSeconds(0);
            this.tb1.Text = TimeSpan.FromSeconds(0).ToString();

            bt_StartTimer.IsEnabled = false;
            bt_CancelTimer.IsEnabled = false;
            
            if (ScheduledActionService.Find("timerremind") != null)
                ScheduledActionService.Remove("timerremind");

            if (IsolatedStorageSettings.ApplicationSettings.Contains("TimerData1"))
            {
                IsolatedStorageSettings.ApplicationSettings.Remove("TimerData1");
                IsolatedStorageSettings.ApplicationSettings.Remove("TimerData2");
                IsolatedStorageSettings.ApplicationSettings.Remove("TimerData3");
            }

            tb2.Text = lv;
            tb3.Text = "Descript = " + descrip;
            tb4.Text = "count = " + count;         
        }

       

        private void testx()
        {
            string message = "Time Out !!!";
            //stop sound here
            this.mesound.Stop();
            ShakeGesturesHelper.Instance.Active = false;
            result = MessageBox.Show(descrip, message, buttons);
            count = 0;
            bt_StartTimer.IsEnabled = false;
            bt_CancelTimer.IsEnabled = false;

            BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/temp.png", UriKind.Relative));
            meter.Source = myBitmapImage;

            Svalue = "";
        }

        void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)
        {
            mesound.Play();
        }
        #endregion

        #region chk LV
        void Instance_ShakeGesture(object sender, ShakeGestureEventArgs e)
        {
            tb2.Dispatcher.BeginInvoke(() =>
            {
                // start sound here
                if (lv == "1")
                {
                    if (count < 20)
                    {
                        tb4.Text = "count = " + count;
                        count++;
                        meterchk();
                    }
                    else
                    {
                        testx();
                    }
                }
                else if (lv == "2")
                {
                    if (count < 30)
                    {
                        tb4.Text = "count = " + count;
                        count++;
                        meterchk2();
                    }
                    else
                    {
                        testx();
                    }
                }
                else if (lv == "3")
                {
                    if (count < 40)
                    {
                        tb4.Text = "count = " + count;
                        count++;
                        meterchk3();
                    }
                    else
                    {
                        testx();
                    }
                }

            });
        }
        #endregion

        #region meter LV1 20t
        private void meterchk()
        {
            if (count <= 1)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/2.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 2)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/4.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 4)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/6.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 6)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/8.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 8)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/10.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 10)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/12.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 12)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/14.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 15)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/16.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 18)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/17.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
        }
        #endregion

        #region meter LV2 30t
        private void meterchk2()
        {
            if (count <= 1)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/2.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 3)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/4.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 4)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/6.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 6)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/8.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 8)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/9.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 10)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/10.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 12)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/11.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 15)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/12.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 18)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/13.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 20)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/14.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 22)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/15.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 24)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/16.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 28)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/17.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
        }
        #endregion

        #region meter LV3 40t
        private void meterchk3()
        {
            if (count <= 1)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/2.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 3)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/4.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 6)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/6.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 9)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/8.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 12)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/9.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 15)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/10.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 18)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/11.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 21)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/12.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 24)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/13.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 27)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/14.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 30)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/15.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 33)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/16.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
            else if (count <= 36)
            {
                BitmapImage myBitmapImage = new BitmapImage(new Uri("/Assets/meterimg/17.png", UriKind.Relative));
                meter.Source = myBitmapImage;
            }
        }
        #endregion

        #region Start Method
        private void startpro() 
        {
            count = 0;
            if (this.dispatcherTimer == null)
            {
                this.dispatcherTimer = new DispatcherTimer();
                this.dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100);
                this.dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);

            }
            if (this.EndTime == DateTime.MinValue)
            {
                this.EndTime = DateTime.Now + TimeSpan.Parse(spanx);
            }

            this.dispatcherTimer.Start();
            
            Svalue = "on";

            if (!setvalue.Contains("Setvalue"))
            {
                setvalue.Add("Setvalue", Svalue);
            }
            else
            {
                setvalue["Setvalue"] = Svalue;
            }
        }

        private void stoppro()
        {
            this.dispatcherTimer.Stop();
            this.EndTime = DateTime.Now;
            this.timeSpan.Value = TimeSpan.FromSeconds(0);
            count = 0;
            ShakeGesturesHelper.Instance.Active = false;
            Svalue = "off";

            if (!setvalue.Contains("Setvalue"))
            {
                setvalue.Add("Setvalue", Svalue);
            }
            else
            {
                setvalue["Setvalue"] = Svalue;
            }

            if (ScheduledActionService.Find("timerremind") != null)
                ScheduledActionService.Remove("timerremind");

        }
        #endregion
    }
}